import Link from "next/link"
import React, {useEffect} from "react";
import {NextRouter, useRouter} from "next/router";

const loadWeJsSdk = (() => {
    let done = false
    return () => {
        if (done || typeof window === "undefined") {
            return
        }
        done = true
        const el = document.createElement('script') as HTMLScriptElement
        el.src = 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js'
        document.body.appendChild(el)
    }
})()

const beforeRouteStart = ({router, to}: { router: NextRouter, to: string }): void | boolean => {
    let path = to
    if (path.indexOf(router.basePath) === 0) {
        path = path.replace(router.basePath, '')
        if (path.indexOf('/') === 0) {
            path = path.slice(1)
        }
    }
    const match = path.match(/pdp\/(.+)/)
    console.log('match pdp', match)
    if (!!match) {
        const id = match[1]
        const Win = window as any
        const {__wxjs_environment, wx} = Win
        if (__wxjs_environment === 'miniprogram') {
            /*当前是小程序，走小程序跳转*/
            wx.miniProgram.navigateTo({url: `/pages/cms/cms-detail?id=${id}`})
            return false
        }
    }
}

export const NextLink: React.FC<{ href: string, attrs?: any }> = (props) => {
    const router = useRouter()
    useEffect(() => loadWeJsSdk(), [])
    return (
        <Link href={props.href}>
            <a {...props.attrs} onClick={(e) => {
                const flag = beforeRouteStart({router, to: props.href})
                if (flag === false) {
                    e.stopPropagation()
                    e.preventDefault()
                }
            }}>
                {props.children}
            </a>
        </Link>
    )
}